# 登录认证的装饰器
import jwt
from django.http import JsonResponse
from django.conf import settings

from user.models import UserProfile

# 登录认证的装饰器
from django.http import JsonResponse
import jwt
from django.conf import settings
from user.models import UserProfile


def login_check(fn):
    def wrap(request, *args, **kwargs):
        # 1 获取前端提交的token
        token = request.META.get('HTTP_AUTHORIZATION')
        print(token)
        if not token:
            result = {'code': 403, 'error': '请登录'}
            return JsonResponse(result)
        # 2 校验token
        try:
            payload = jwt.decode(token,
                                 settings.JWT_TOKEN_KEY)
        except Exception as e:
            print('the error is %s' % e)
            result = {'code': 403, 'error': '请登录'}
            return JsonResponse(result)
        # 从payload获取私用声明
        username = payload['username']
        # 根据用户名获取用户对象
        user = UserProfile.objects.get(username=username)
        # 将登录的用户对象添加到请求对象中
        request.myuser = user
        # 调用装饰器修饰的函数
        return fn(request, *args, **kwargs)

    return wrap


def get_user_by_request(request):
    # 1 获取前端提交的token
    token = request.META.get('HTTP_AUTHORIZATION')
    # 2 表示访问者是游客
    if not token:
        return None
    # 3 token存在,校验token,,校验不通过,表示登录失败,等同游客
    try:
        payload = jwt.decode(token,
                             settings.JWT_TOKEN_KEY)
    except:
        return None
    # 4 token校验通过
    username = payload['username']
    return username
